﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Fsb.Utility;

namespace VideoCache.Spider.FileFetchers
{
    class TudouFetcher : IFetcher
    {
        const string JSON_URL = "http://v2.tudou.com/v.action?it={0}";

        public FetcherResult[] GetFiles(string url)
        {
            string html = HttpUtility.Get(url, Encoding.GetEncoding("gb2312"));
            
            int iid = GetIid(html);

            string xml = HttpUtility.Get(string.Format(JSON_URL, iid), Encoding.UTF8);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNodeList list = doc.SelectNodes(@"//v//a//f");

            List<FetcherResult> resultList = new List<FetcherResult>();
            if (list != null)
            {
                foreach (XmlNode node in list)
                {
                    int brt;
                    if (int.TryParse(node.Attributes["brt"].Value, out brt))
                    {
                        FetcherResult result = new FetcherResult();
                        switch (brt)
                        {
                            case 2:
                                result.Resolution = Resolution.Level_2;
                                break;
                            case 3:
                                result.Resolution = Resolution.Level_3;
                                break;
                            case 4:
                                result.Resolution = Resolution.Level_4;
                                break;
                        }

                        result.Files.Add(node.InnerText.Trim());

                        resultList.Add(result);
                    }
                }
            }

            if (list.Count == 0)
            {
                throw new FetcherException("无法获取视频下载地址，视频不存在或已删除。");
            }

            return resultList.ToArray();
        }

        private int GetIid(string html)
        {
            string json = StringUtility.SubString(html, "itemData=", ";");
            
            ItemData data = JsonUtility.Object<ItemData>(json);

            return data.Iid;
        }

        private class ItemData
        {
            public int Iid { get; set; }
        }
    }
}
